package com.pluto.stack;

import java.util.Iterator;

/**
 * 栈的数组实现
 * 可动态调整数组大小
 */
public class ResizingArrayStack<Item> implements Iterable<Item> {

    private Item[] a = (Item[]) new Object[1];

    private int N = 0;

    /**
     * 返回栈是否为空
     * @return
     */
    public boolean isEmpty() {
        return N == 0;
    }

    /**
     * 返回栈的大小
     * @return
     */
    public int size() {
        return N;
    }

    /**
     * 调整内部数组大小
     * @param max
     */
    private void resize(int max) {
        Item[] temp = (Item[]) new Object[max];
        for (int i = 0; i < N; i++) {
            temp[i] = a[i];
        }
        a = temp;
    }

    /**
     * 入栈操作
     * @param item
     */
    public void push(Item item) {
        if (N == a.length) {
            resize(2 * a.length);
        }
        a[N++] = item;
    }

    /**
     * 出栈操作
     * @return
     */
    public Item pop() {
        Item item = a[--N];
        a[N] = null;
        if (N > 0 && N == a.length / 4) {
            resize(a.length / 2);
        }
        return item;
    }

    public static void main(String[] args) {
        ResizingArrayStack<String> resizingArrayStack = new ResizingArrayStack<>();
        resizingArrayStack.push("hello");
        resizingArrayStack.push("world");
        for (String s : resizingArrayStack) {
            System.out.println(s);
        }
    }

    /**
     * 实现迭代器
     * @return
     */
    @Override
    public Iterator<Item> iterator() {
        return new ReverseArrayIterator();
    }

    private class ReverseArrayIterator implements Iterator<Item> {

        private int i = N;

        @Override
        public boolean hasNext() {
            return i > 0;
        }

        @Override
        public Item next() {
            return a[--i];
        }
    }
}
